# app/routes/progress.py
from fastapi import APIRouter, HTTPException
from app.config.base_setting import backend_logger
from app.utils.remote_ssh import ssh_connect, read_remote_progress_file

router = APIRouter()

# ────────────────────────────────────────────────────────────────
# Route: GET /progress/batch/{task_id}
# Purpose: Retrieve the OCR batch processing progress for the specified task_id
# Source: Read the remote progress_ {task_id}. json file
# ────────────────────────────────────────────────────────────────
@router.get("/progress/batch/{task_id}")
def get_ocr_batch_progress(task_id: str):
    """
    Return the content of the progress file generated by the remote OCR script.
    -Each task_id corresponds to an independent progress_ {task_id}. json
    -Front end polling this interface can obtain real-time progress
    """
    backend_logger.info(f"📊 [progress.py] Starting batch progress fetch for task: {task_id}")
    client = ssh_connect()
    if not client:
        backend_logger.error("🚨 [progress.py] SSH connection failed for progress check")
        raise HTTPException(status_code=503, detail="No available remote server")

    try:
        backend_logger.debug(f"🔐 [progress.py] Connected to SSH. Attempting to read progress file for: {task_id}")
        progress_data = read_remote_progress_file(client, task_id)

        if not progress_data:
            backend_logger.warning(f"⚠️ [progress.py] Empty or missing progress data for task: {task_id}")
            return {
                "task_id": task_id,
                "percent": 0,
                "status": "not_started",
                "message": "No progress data available."
            }

        backend_logger.debug(f"✅ [progress.py] Progress data retrieved: {progress_data}")
        return progress_data

    except Exception as e:
        backend_logger.exception(f"💥 [progress.py] Error while fetching batch progress for {task_id}: {str(e)}")
        raise HTTPException(status_code=500, detail="Failed to fetch progress data")

    finally:
        client.close()
        backend_logger.debug(f"🔚 [progress.py] SSH connection closed for task: {task_id}")


# ────────────────────────────────────────────────────────────────
# Route: GET /progress/task/{task_id}
# Purpose: Get task status summary (for task management panel or notifications)
# ────────────────────────────────────────────────────────────────
@router.get("/progress/task/{task_id}")
def get_task_summary(task_id: str):
    """
    Quickly return the overall status and completion percentage of the task.
    Can be used for the front-end top progress bar or task list.
    """
    backend_logger.info(f"📌 [progress.py] Requesting task summary for: {task_id}")
    client = ssh_connect()
    if not client:
        backend_logger.error("🚨 [progress.py] SSH connection failed for task summary")
        raise HTTPException(status_code=503, detail="No available remote server")

    try:
        backend_logger.debug(f"🔐 [progress.py] Connected to SSH. Reading progress for summary: {task_id}")
        progress_data = read_remote_progress_file(client, task_id)

        if not progress_data:
            backend_logger.warning(f"⚠️ [progress.py] No progress found for task summary: {task_id}")
            return {
                "task_id": task_id,
                "percent": 0,
                "status": "not_started",
                "message": "No progress data available."
            }

        percent = progress_data.get("percent", 0)
        status = progress_data.get("status", "in_progress")
        message = progress_data.get("message", "")

        backend_logger.debug(f"📦 [progress.py] Task {task_id} summary: {percent}%, {status}, {message}")
        return {
            "task_id": task_id,
            "percent": percent,
            "status": status,
            "message": message,
            # "files": progress_data.get("files", [])  # 去掉文件列表，轻量级端口，备用
        }

    except Exception as e:
        backend_logger.exception(f"💥 [progress.py] Failed to summarize task {task_id}: {str(e)}")
        raise HTTPException(status_code=500, detail="Failed to get task summary")

    finally:
        client.close()
        backend_logger.debug(f"🔚 [progress.py] SSH connection closed for summary: {task_id}")

